/**
 *
 */
package com.czmh.etc.onlinepubsys.services.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.czmh.etc.common.core.utils.Sequence;
import com.czmh.etc.onlinepubsys.constants.GlobalStatusCode;
import com.czmh.etc.onlinepubsys.dto.EtcApplyDto;
import com.czmh.etc.onlinepubsys.dto.EtcIdcardDto;
import com.czmh.etc.onlinepubsys.dto.EtcVehiclelicenseDto;
import com.czmh.etc.onlinepubsys.dto.UpdateUserInfo;
import com.czmh.etc.onlinepubsys.dto.UserInfo;
import com.czmh.etc.onlinepubsys.exceptions.EtcUserException;
import com.czmh.etc.onlinepubsys.json.JsonResult;
import com.czmh.etc.onlinepubsys.maper.EtcApplyMapper;
import com.czmh.etc.onlinepubsys.maper.EtcCarMapper;
import com.czmh.etc.onlinepubsys.maper.EtcEcardcallbackpageMapper;
import com.czmh.etc.onlinepubsys.maper.EtcEcardcheckinMapper;
import com.czmh.etc.onlinepubsys.maper.EtcEcardviewMapper;
import com.czmh.etc.onlinepubsys.maper.EtcIdcardMapper;
import com.czmh.etc.onlinepubsys.maper.EtcUserMapper;
import com.czmh.etc.onlinepubsys.maper.EtcVehiclelicenseMapper;
import com.czmh.etc.onlinepubsys.maper.EtcWechatauthorizedMapper;
import com.czmh.etc.onlinepubsys.model.EtcApply;
import com.czmh.etc.onlinepubsys.model.EtcCar;
import com.czmh.etc.onlinepubsys.model.EtcEcardcallbackpage;
import com.czmh.etc.onlinepubsys.model.EtcEcardcheckin;
import com.czmh.etc.onlinepubsys.model.EtcEcardresult;
import com.czmh.etc.onlinepubsys.model.EtcEcardview;
import com.czmh.etc.onlinepubsys.model.EtcIdcard;
import com.czmh.etc.onlinepubsys.model.EtcUser;
import com.czmh.etc.onlinepubsys.model.EtcVehiclelicense;
import com.czmh.etc.onlinepubsys.model.EtcWechatauthorized;
import com.czmh.etc.onlinepubsys.request.CheckExchangeNoRequest;
import com.czmh.etc.onlinepubsys.request.EtcEcardcheckinEditRequest;
import com.czmh.etc.onlinepubsys.respository.EtcEcardcallbackpageRepository;
import com.czmh.etc.onlinepubsys.respository.EtcEcardresultRepository;
import com.czmh.etc.onlinepubsys.services.EtcUserInfoSevice;
import com.czmh.etc.onlinepubsys.services.ISsoService;
import com.czmh.etc.onlinepubsys.utils.JsonResultUtil;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * @描述：EtcUserInfoSeviceImpl
 * @author： Seven.
 * @创建日期：Jun 10, 2019 6:35:20 PM.
 * @版本：1.0.0
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class EtcUserInfoSeviceImpl implements EtcUserInfoSevice {

    @Value("${etc.applyLimit}")
    private int                            applyLimit;

    @Autowired
    private EtcUserMapper                  etcUserMapper;
    @Autowired
    private EtcWechatauthorizedMapper      etcWechatauthorizedMapper;
    @Autowired
    private EtcApplyMapper                 etcApplyMapper;
    @Autowired
    private EtcIdcardMapper                etcIdcardMapper;
    @Autowired
    private EtcVehiclelicenseMapper        etcVehiclelicenseMapper;
    @Autowired
    private EtcCarMapper                   etcCarMapper;
    @Autowired
    private EtcEcardcallbackpageRepository etcEcardcallbackpageRepository;
    @Autowired
    private EtcEcardresultRepository       etcEcardresultRepository;
    @Autowired
    private EtcEcardcallbackpageMapper     etcEcardcallbackpageMapper;
    @Autowired
    private RedisUtil                      redisUtil;
    @Autowired
    private ISsoService ISsoService;
    @Autowired
    private EtcEcardcheckinMapper          etcEcardcheckinMapper;
    @Autowired
    private EtcEcardviewMapper             etcEcardviewMapper;
    @Autowired
    private WxMpService                    wxMpService;
    @Autowired
    private EtcUserInfoSevice         etcUserInfoSevice;

    @Override
    public EtcUser saveUserInfo(JSONObject userInfoJSON) {
        EtcUser dbuser = etcUserMapper.getByUnionid(userInfoJSON.get("unionId") == null ? "" : userInfoJSON.get("unionId").toString());
        EtcUser etcUser = new EtcUser();
        EtcWechatauthorized wechatauthorized = new EtcWechatauthorized(Sequence.getId());
        wechatauthorized.setCity(userInfoJSON.get("city").toString());
        wechatauthorized.setCountry(userInfoJSON.get("country").toString());
        wechatauthorized.setCreatetime(new Date());
        wechatauthorized.setHeadimgurl(userInfoJSON.get("avatarUrl").toString());
        wechatauthorized.setNickname(userInfoJSON.get("nickName").toString());
        wechatauthorized.setOpenid(userInfoJSON.get("openId").toString());
        wechatauthorized.setProvince(userInfoJSON.get("province").toString());
        wechatauthorized.setRefreshtime(new Date());
        wechatauthorized.setSex(Integer.valueOf(userInfoJSON.get("gender").toString()));
        wechatauthorized.setUnionid(userInfoJSON.get("unionId") == null ? "" : userInfoJSON.get("unionId").toString());
        EtcWechatauthorized e = etcWechatauthorizedMapper.getByUnionId(userInfoJSON.getString("unionId"));
        if(e == null){
            etcWechatauthorizedMapper.insert(wechatauthorized);
        }
        if (dbuser == null) {
            etcUser.setUser_id(Sequence.getId());
            etcUser.setCreate_time(new Date());
            etcUser.setUpdate_time(new Date());
            etcUser.setUser_headimg(wechatauthorized.getHeadimgurl());
            etcUser.setUser_sex(wechatauthorized.getSex());
            //补充入库用户昵称
            etcUser.setNickName(wechatauthorized.getNickname());
            etcUser.setUser_status(0);
            etcUser.setOpenid(userInfoJSON.get("openId").toString());
            etcUser.setUnionid(userInfoJSON.get("unionId") == null ? "" : userInfoJSON.get("unionId").toString());
            // 1.初始化ETC用户信息
            etcUserMapper.insert(etcUser);
            // 2.保存微信授权信息
            EtcWechatauthorized etcWechatauthorized = etcWechatauthorizedMapper.getByUnionId(userInfoJSON.getString("unionId"));
            if(etcWechatauthorized == null){
                wechatauthorized.setUser_id(etcUser.getUser_id());
                etcWechatauthorizedMapper.insert(wechatauthorized);
            }
        } else {
            etcUser.setUser_id(dbuser.getUser_id());
            wechatauthorized.setUser_id(etcUser.getUser_id());
            etcUser.setUpdate_time(new Date());
            //补充入库用户昵称
            etcUser.setNickName(wechatauthorized.getNickname());
            etcUser.setUser_headimg(wechatauthorized.getHeadimgurl());
            etcUser.setUser_sex(wechatauthorized.getSex());
            etcUser.setOpenid(userInfoJSON.get("openId").toString());
            etcUser.setUnionid(userInfoJSON.get("unionId") == null ? "" : userInfoJSON.get("unionId").toString());
            etcUserMapper.update(etcUser);
            etcWechatauthorizedMapper.update(wechatauthorized);
        }
        return etcUser;
    }

    @Override
    public EtcUser queryUserByMobile(String mobile) {
        Map<String, Object> params = new HashMap<String, Object>(0);
        params.put("user_phone", mobile);
        EtcUser etcUser = etcUserMapper.getAll(params).isEmpty() ? null : etcUserMapper.getAll(params).get(0);
        return etcUser;
    }

    @Override
    public EtcApply submitApplyInfo(String user_id, EtcApplyDto apply, EtcIdcardDto idcard,
            EtcVehiclelicenseDto vehiclelicense) throws EtcUserException {
        // 身份证姓名和行驶证姓名不一致则返回错误提示
//        if (!idcard.getName().equals(vehiclelicense.getOwner())) {
//            throw new EtcUserException(GlobalStatusCode.FAILED, "身份证姓名和行驶证所有人不一致");
//        }
        // 判断当前身份证是否已经提交过申请，如果已经有申办过则不能再申请
        Map<String, Object> params = new HashMap<String, Object>(0);
        params.put("apply_idcard", idcard.getNum());
        List<EtcApply> applies = etcApplyMapper.getAll(params);
//        if (!applies.isEmpty()) {
//            throw new EtcUserException(GlobalStatusCode.FAILED, "该身份证号已申办过ETC");
//        }
        params.clear();
        params.put("user_id", user_id);
        applies = etcApplyMapper.getAll(params);
        // 如果该用户提交申办的ETC数量大于申办限制则提示该用户不能再办理了
        if (applies.size() > applyLimit) {
            throw new EtcUserException(GlobalStatusCode.FAILED, "该用户申办ETC数量超过限制");
        }
        // 封装身份证信息
        EtcIdcard etcIdcard = new EtcIdcard(Sequence.getId());
        BeanUtils.copyProperties(idcard, etcIdcard);
        etcIdcard.setUser_id(user_id);
        etcIdcard.setCreate_time(new Date());
        etcIdcard.setUpdate_time(new Date());
        // 封装行驶证信息
        EtcVehiclelicense etcVehiclelicense = new EtcVehiclelicense(Sequence.getId());
        BeanUtils.copyProperties(vehiclelicense, etcVehiclelicense);
        // 封装车辆信息
        EtcCar etcCar = new EtcCar(Sequence.getId());
        etcCar.setCarclass(etcVehiclelicense.getVehicle_type());
        etcCar.setCarenginenum(etcVehiclelicense.getEngine_num());
        etcCar.setCarlicensenum(etcVehiclelicense.getPlate_num());
        etcCar.setCarmodel(etcVehiclelicense.getModel());
        etcCar.setCaropera(etcVehiclelicense.getUse_character());
        etcCar.setCarweight(etcVehiclelicense.getAppproved_passenger_capacity());
//        String overall_dimension = etcVehiclelicense.getOverall_dimension();
//        String[] size = overall_dimension.split("X");
//        etcCar.setVehweight(size[0]);
//        etcCar.setVehwidth(size[1]);
//        etcCar.setVehheight(size[2].substring(0, 4));
        etcCar.setWheelnum("4");
        etcCar.setUser_id(user_id);
        etcCar.setUpdate_time(new Date());
        etcCar.setCreate_time(new Date());
        // 轴距
        etcCar.setWheelbase("0");
        // 轴数
        etcCar.setAxlenum("2");
        // 车辆颜色
        etcCar.setCarcolor("");
        // 车辆车牌底色
        etcCar.setCarlicensecolor(apply.getApply_carlicencetyoe());
        // 设置行驶证的车辆信息ID
        etcVehiclelicense.setCar_id(etcCar.getId());
        // 封装申请信息
        EtcApply etcApply = new EtcApply(Sequence.getId());
        BeanUtils.copyProperties(apply, etcApply);
        etcApply.setUser_id(user_id);
        etcApply.setCreatetime(new Date());
        etcApply.setUpdatetime(new Date());
        // 设置状态为填写收货地址
        etcApply.setApply_status(2);
        etcApply.setCar_id(etcCar.getId());
        etcApply.setAddress(idcard.getAddress());
        // 查询信用卡提交申请结果信息
        if (apply.getApply_channel() != null && apply.getApply_channel() == 2) {
            // 判断流水号不为空再进行对应更新操作
            if (StringUtils.isNotEmpty(apply.getSerialnum())) {
                params.clear();
                params.put("serialnum", apply.getSerialnum());
                List<EtcEcardcallbackpage> etcEcardcallbackpageList = etcEcardcallbackpageMapper.getAll(params);
                if (!etcEcardcallbackpageList.isEmpty()) {
                    EtcEcardcallbackpage etcEcardcallbackpage = etcEcardcallbackpageList.get(0);
                    etcApply.setApplystatus(etcEcardcallbackpage.getApplystatus());
                }
                // 更新信用卡登记信息ETC申请状态
                EtcEcardview ecardview = new EtcEcardview();
                ecardview.setSerialnum(apply.getSerialnum());
                ecardview.setCompleteetcapply(1);
                ecardview.setUpdatetime(new Date());
                etcEcardviewMapper.updateByserialNum(ecardview);
                EtcEcardcheckin etcEcardcheckin = new EtcEcardcheckin();
                etcEcardcheckin.setSerialnum(apply.getSerialnum());
                etcEcardcheckin.setCompleteetcapply(1);
                etcEcardcheckin.setUpdatetime(new Date());
                etcEcardcheckinMapper.updateByserialNum(etcEcardcheckin);
            }
        }
        // 保存数据库
        etcIdcardMapper.insert(etcIdcard);
        etcCarMapper.insert(etcCar);
        etcApplyMapper.insert(etcApply);
        etcVehiclelicenseMapper.insert(etcVehiclelicense);
        return etcApply;
    }

    @Override
    public String saveEcardCheckin(String userId) {
        EtcEcardcheckin etcEcardcheckin = new EtcEcardcheckin(Sequence.getId());
        etcEcardcheckin.setUserid(userId);
        etcEcardcheckin.setSerialnum( UUID.randomUUID().toString());
        etcEcardcheckin.setCreatetime(new Date());
        etcEcardcheckin.setUpdatetime(new Date());
        etcEcardcheckinMapper.insert(etcEcardcheckin);
        return etcEcardcheckin.getSerialnum();
    }

    @Override
    public void saveEcardCallbackPageParam(EtcEcardcallbackpage etcEcardcallbackpage, String authorization) {
        String userinfo = redisUtil.get(authorization).toString();
        JSONObject jsonObject = JSONObject.parseObject(userinfo);
        EtcUser etcUser = JSONObject.parseObject(jsonObject.get("etcUserInfo").toString(), EtcUser.class);
        etcEcardcallbackpage.setUserId(etcUser.getUser_id());
        etcEcardcallbackpageRepository.save(etcEcardcallbackpage);
    }

    @Override
    public void saveEcardNotifyParam(EtcEcardresult etcEcardresult) {
        etcEcardresultRepository.save(etcEcardresult);
    }

    @Override
    public EtcUser loginByMobile(String mobile) {
        Map<String, Object> params = new HashMap<String, Object>(0);
        params.put("user_phone", mobile);
        EtcUser dbuser = etcUserMapper.getAll(params).isEmpty() ? null : etcUserMapper.getAll(params).get(0);
        EtcUser etcUser = new EtcUser();
        etcUser.setUser_phone(mobile);
        etcUser.setUser_loginname(mobile);
        etcUser.setUser_phone(mobile);
        if (dbuser == null) {
            etcUser.setUser_id(Sequence.getId());
            etcUser.setCreate_time(new Date());
            etcUser.setUpdate_time(new Date());
            etcUser.setUser_status(0);
            // 1.初始化ETC用户信息
            etcUserMapper.insert(etcUser);
            return etcUser;
        } else {
           return dbuser;
        }
    }

    @Override
    public JsonResult bindMobile(com.czmh.etc.onlinepubsys.feign.newrun.entity.EtcUser niurunEtcUser) {
        // 手机号+验证码登录
        String mobile = niurunEtcUser.getMobile();
        String validCode = niurunEtcUser.getValidCode();
        String openid = niurunEtcUser.getOpenid();
        // 检查手机验证码是否正确
        String redisValidCode = redisUtil.get(mobile).toString();
        if (StringUtils.isNotEmpty(validCode) && StringUtils.isNotEmpty(redisValidCode) && (validCode.equals(redisValidCode))) {
            // 注销验证码
            redisUtil.del(mobile);
            // 2.查询该openid是否已绑定过手机号
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("openid", openid);
            List<EtcUser> all = etcUserMapper.getAll(params);
            if (all.isEmpty()) {
                EtcUser etcUser = new EtcUser();
                etcUser.setUser_phone(mobile);
                etcUser.setUser_status(0);
                etcUser.setUser_loginname(mobile);
                etcUser.setUser_headimg(niurunEtcUser.getHeadimgurl());
                // 查找微信授权信息是否存在，存在则设置性别以及unionID
                params.clear();
                params.put("openid", openid);
                List<EtcWechatauthorized> all2 = etcWechatauthorizedMapper.getAll(params);
                if (!all2.isEmpty()) {
                    etcUser.setUser_sex(all2.get(0).getSex());
                    etcUser.setUnionid(all2.get(0).getUnionid());
                }
                // 3.查询手机号是否已注册用户，没注册则注册一个用户，已注册则更新openid
                params.clear();
                params.put("user_phone", mobile);
                all = etcUserMapper.getAll(params);
                if (!all.isEmpty() && all.size() == 1 && StringUtils.isEmpty(all.get(0).getOpenid())) {
                    // 4.绑定手机号
                    EtcUser update = all.get(0);
                    etcUser.setUser_id(update.getUser_id());
                    update.setOpenid(openid);
                    update.setUser_sex(etcUser.getUser_sex());
                    update.setUser_headimg(etcUser.getUser_headimg());
                    update.setUnionid(etcUser.getUnionid());
                    etcUserMapper.update(update);
                } else {
                    // 注册新用户
                    etcUser.setOpenid(openid);
                    etcUser.setCreate_time(new Date());
                    etcUser.setUpdate_time(new Date());
                    etcUser.setUser_id(Sequence.getId());
                    etcUserMapper.insert(etcUser);
                }
                // 更新微信授权信息userid
                if (!all2.isEmpty()) {
                    EtcWechatauthorized update = new EtcWechatauthorized(all2.get(0).getAuthorizedid());
                    update.setUser_id(etcUser.getUser_id());
                    etcWechatauthorizedMapper.update(update);
                }
                // 登录纽润接口
                return ISsoService.loginByMobile(mobile);
            } else {
                EtcUser dbUser = all.get(0);
                if (StringUtils.isNotEmpty(dbUser.getUser_phone())) {
                    return JsonResultUtil.toErrorResult("已绑定过手机号");
                } else {
                    EtcUser update = new EtcUser(dbUser.getUser_id());
                    update.setUser_phone(mobile);
                    update.setUser_loginname(mobile);
                    etcUserMapper.update(update);
                    // 登录纽润接口
                    return ISsoService.loginByMobile(mobile);
                }
            }
        } else {
            return JsonResultUtil.toErrorResult("手机验证码不正确！");
        }
    }

    @Override
    public JsonResult saveEcardCheckin(EtcEcardcheckinEditRequest request) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("check_idcard", request.getCheck_idcard());
        params.put("card_type", request.getCard_type());
        List<EtcEcardcheckin> list = etcEcardcheckinMapper.getAll(params);
        if (list.isEmpty()) {
            EtcEcardcheckin etcEcardcheckin = new EtcEcardcheckin(Sequence.getId());
            BeanUtils.copyProperties(request, etcEcardcheckin);
            etcEcardcheckin.setCreatetime(new Date());
            etcEcardcheckin.setUpdatetime(new Date());
            etcEcardcheckinMapper.insert(etcEcardcheckin);
            return JsonResultUtil.toResult(etcEcardcheckin);
        } else {
            return JsonResultUtil.toResult("该证件号已经登记过改银行信息，请勿重复填写");
        }
    }

    @Override
    public JsonResult getEcardCheckin(String userId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userid", userId);
        params.put("orderField", "createtime");
        params.put("orderSeq", "DESC");
        params.put("completeetcapply", 0);
        List<EtcEcardview> list = etcEcardviewMapper.getAll(params);
        if (list.isEmpty()) {
            return JsonResultUtil.toResult();
        } else {
            String serialnum = list.get(0).getSerialnum();
            params.clear();
            params.put("serialnum", serialnum);
            List<EtcEcardcheckin> list2 = etcEcardcheckinMapper.getAll(params);
            if (list2.isEmpty()) {
                EtcEcardcheckin checkIn = new EtcEcardcheckin();
                checkIn.setUserid(userId);
                checkIn.setSerialnum(serialnum);
                return JsonResultUtil.toResult(checkIn);
            } else {
                return JsonResultUtil.toResult(list2.get(0));
            }
        }
    }

    @Override
    public JsonResult checkcreditcard(String userId, Integer card_type) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userid", userId);
        params.put("card_type", card_type);
        List<EtcEcardcheckin> list = etcEcardcheckinMapper.getAll(params);
        if (!list.isEmpty()) {
            return JsonResultUtil.toResult(list.get(0));
        }
        return JsonResultUtil.toResult();
    }

    @Override
    public String saveEcardView(String userId, Integer card_type, String ip) {
        String serialnum = UUID.randomUUID().toString();
        EtcEcardview model = new EtcEcardview(Sequence.getId());
        model.setUserid(userId);;
        model.setIp(ip);
        model.setCard_type(card_type);
        model.setSerialnum(serialnum);
        model.setCreatetime(new Date());
        model.setUpdatetime(new Date());
        etcEcardviewMapper.insert(model);
        return serialnum;
    }

    @Override
    public JsonResult checkexchangeNo(CheckExchangeNoRequest request) {
        String redisValidCode = redisUtil.get(request.getCheck_phone()).toString();
        String validCode = request.getValidCode();
        if (StringUtils.isNotEmpty(validCode) && StringUtils.isNotEmpty(redisValidCode) && (validCode.equals(redisValidCode))) {
         // 注销验证码
            redisUtil.del(request.getCheck_phone());
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("check_idcard", request.getCheck_idcard());
            params.put("check_phone", request.getCheck_phone());
            params.put("card_type", 1);
            List<EtcEcardcheckin> list = etcEcardcheckinMapper.getAll(params);
            if (!list.isEmpty()) {
                EtcEcardcheckin ecardcheckin = list.get(0);
                return JsonResultUtil.toResult(ecardcheckin.getSerialnum());
            } else {
                return JsonResultUtil.toResult("没有此证件号的登记信息，请核对后重新填写");
            }
        } else {
           return JsonResultUtil.toResult("验证码错误！");
        }
    }

    @Override
    public JsonResult updatexchangeNo(String serialNum) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("serialnum", serialNum);
        List<EtcEcardcheckin> list = etcEcardcheckinMapper.getAll(params);
        if (!list.isEmpty()) {
            EtcEcardcheckin etcEcardcheckin = new EtcEcardcheckin();
            etcEcardcheckin.setSerialnum(serialNum);
            etcEcardcheckin.setExchange(1);
            etcEcardcheckinMapper.updateByserialNum(etcEcardcheckin );
            return JsonResultUtil.toResult("核销成功！");
        } else {
            return JsonResultUtil.toResult("找不到该流水号的登记信息，请重新输入");
        }
    }

    @Override
    public EtcUser saveWechatInfo(WxMpUser wpMpUser) {
        log.info(String.format("[微信用户信息] \"%s\"", wpMpUser));
        Map<String, Object> params = new HashMap<String, Object>(0);
        params.put("openid", wpMpUser.getOpenId());
        EtcUser dbuser = etcUserMapper.getByUnionid(wpMpUser.getUnionId());
        if (dbuser != null) {
           EtcUser update = new EtcUser(dbuser.getUser_id());
           update.setSubscribe(wpMpUser.getSubscribe() == null ? 0 : wpMpUser.getSubscribe() ? 1 : 0);
           etcUserMapper.update(update);
           return dbuser;
        } else {
            EtcUser etcUser = new EtcUser(Sequence.getId());
            etcUser.setUser_headimg(wpMpUser.getHeadImgUrl());
            etcUser.setUser_sex(wpMpUser.getSex());
            etcUser.setUser_status(0);
            etcUser.setOpenid(wpMpUser.getOpenId());
            etcUser.setUnionid(wpMpUser.getUnionId());
            etcUser.setSubscribe(wpMpUser.getSubscribe() == null ? 0 : wpMpUser.getSubscribe() ? 1 : 0);
            etcUser.setCreate_time(new Date());
            etcUser.setUpdate_time(new Date());
            etcUserMapper.insert(etcUser);
            return etcUser;
        }
    }

    @Override
    public JsonResult saveUserInfoByCode(String code) throws WxErrorException {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
        log.info(String.format("[微信用户信息] \"%s\"", wxMpUser));
        EtcUser etcUser = this.saveWechatInfo(wxMpUser);
        Map<String, String> data = new HashMap<String, String>();
        data.put("userId", etcUser.getUser_id());
        data.put("openid", etcUser.getOpenid());
        data.put("nickname", wxMpUser.getNickname());
        data.put("headimgurl", etcUser.getUser_headimg());
        data.put("unionid", etcUser.getUnionid());
        data.put("mobile", etcUser.getUser_phone());
        return JsonResultUtil.toResult(data);
    }

    @Override
    public JsonResult updateUserInfo(UpdateUserInfo userInfo) {
        EtcUser update = new EtcUser();
        BeanUtils.copyProperties(userInfo, update);
        etcUserMapper.update(update);
        return JsonResultUtil.toResult();
    }

    @Override
    public JsonResult users(String userid) {
        UserInfo userInfo = etcUserMapper.getUserInfo(userid);
        return JsonResultUtil.toResult(userInfo);
    }

    @Override
    public EtcUser queryUserInfo(String userId) {
        return etcUserMapper.getById(userId);
    }

    @Override
    public void updateUser(EtcUser etcUser) {
        etcUserMapper.update(etcUser);
    }

    @Override
    public JsonResult updateMobile(String userid, String mobile, String validCode) {
        EtcUser etcUser = etcUserInfoSevice.queryUserByMobile(mobile);
        if(null != etcUser){
            return JsonResultUtil.toErrorResult("手机号码已绑定用户！");
        }
        // 检查手机验证码是否正确
        String redisValidCode = "";
        Object o = redisUtil.get(mobile);
        if(null != o){
            redisValidCode = o.toString();
        }else{
            return JsonResultUtil.toErrorResult("验证码错误！");
        }
        if (StringUtils.isNotEmpty(validCode) && StringUtils.isNotEmpty(redisValidCode) && (validCode.equals(redisValidCode))) {
            // 注销验证码
            redisUtil.del(mobile);
            EtcUser update = new EtcUser(userid);
            update.setUser_loginname(mobile);
            update.setUser_phone(mobile);
            etcUserMapper.update(update);
        }
        Map<String, Object> data = new HashMap<>();
        return JsonResultUtil.toResult("操作成功！");
    }

    @Override
    public void insert(EtcUser etcUser) {
        etcUserMapper.insert(etcUser);
    }

}
